/**
 * 
 */
package com.wrsr.examsys.card.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.wrsr.examsys.card.service.CardService;
import com.wrsr.examsys.card.service.DiscussService;
import com.wrsr.examsys.card.service.ReDiscussService;
import com.wrsr.examsys.domain.Card;
import com.wrsr.examsys.domain.Discuss;
import com.wrsr.examsys.domain.ReDiscuss;
import com.wrsr.examsys.domain.Student;
import com.wrsr.examsys.domain.Teacher;
import com.wrsr.examsys.valited.StringIsValitedUtils;

/**
 * @author <a href="mailto:2397431783@qq.com">wangruishun</a>
 * @version examsy1.0 2015年5月10日 下午6:15:00
 */
@Controller("cardAction")
@Scope("prototype")
public class CardAction extends ActionSupport implements ServletRequestAware {
	private static final long serialVersionUID = 1409702947543805786L;
	@Resource
	private CardService carService;
	@Resource
	private DiscussService discussService;
	@Resource
	private ReDiscussService reDiscussService;
	private String msg;
	private Card card = new Card();
	private Discuss discuss = new Discuss();
	private final static String WRONG = "wong";
	private final static String LOGIN = "login";
	private HttpServletRequest request;
	private Teacher teacher = new Teacher();
	private Student student = new Student();
	private ReDiscuss reDiscuss = new ReDiscuss();
	private List<Card> cardList = null;
	private List<Discuss> discussList = null;
	private List<ReDiscuss> reDiscussList = null;
	private Integer startIndex = 0;
	private static final Integer LENGTH = 5;
	// 1:加一页 0：减一页
	private String pageFlag = "2";
	private Integer totalPage = 0;
	private Integer pageIndex = 1;
	private String discussId;
	private String cardId;
	private String fromId;
	private Integer discussCount = 0;
	private Integer reDiscussCount = 0;
	private Integer totalCountMsg = 0;
	private Map<String, Object> dataMap;

	public CardAction() {
		dataMap = new HashMap<String, Object>();
	}

	/*
	 * 打开帖子页面
	 */
	public String addCardPage() {
		return SUCCESS;
	}

	public String addCard() {
		// 标题和内容进行验证
		if (!StringIsValitedUtils.isValid(card.getTitle())
				|| !StringIsValitedUtils.isValid(card.getContent())) {
			msg = "*亲，您输入的标题或者内容包含非法字符！";
			return WRONG;
		}
		// 1:学生 0：老师 2：未登录
		int flag;
		try {
			student = (Student) request.getSession().getAttribute("student");
			if (student != null) {
				// 身份为学生
				flag = 1;
				if (student.getEmail() == null) {
					flag = 2;
				}
			} else {
				flag = 2;
			}
		} catch (Exception e) {
			flag = 2;
		}
		if (flag != 1) {
			try {
				teacher = (Teacher) request.getSession()
						.getAttribute("teacher");
				if (teacher != null) {
					// 身份为老师
					flag = 0;
					if (teacher.getEmail() == null) {
						flag = 2;
					}
				} else {
					flag = 2;
				}
			} catch (Exception e) {
				flag = 2;
			}
		}
		if (flag == 2) {
			return LOGIN;
		}
		if (flag == 0) {
			card.setFromId(teacher.getEmail());
			card.setFromType(0);
			card.setFromName(teacher.getTeacherName());
		}
		if (flag == 1) {
			card.setFromId(student.getEmail());
			card.setFromType(1);
			card.setFromName(student.getName());
		}
		carService.saveEntity(card);
		return SUCCESS;
	}

	public String getCardListByPage() {
		int pageIn = (int) pageIndex;
		int toltal = carService.getTotal();
		if (toltal % LENGTH == 0) {
			totalPage = toltal / LENGTH;
		} else {
			totalPage = toltal / LENGTH + 1;
		}
		startIndex = (int) startIndex;
		if ("2".equals(pageFlag)) {
			cardList = carService.getCardByPage(startIndex, LENGTH);
			pageIndex = pageIn;
			return SUCCESS;
		}
		if ("0".equals(pageFlag)) {
			if ((startIndex - LENGTH) < 0) {
				cardList = carService.getCardByPage(startIndex, LENGTH);
				pageIndex = pageIn;
				return SUCCESS;
			} else {
				startIndex = startIndex - LENGTH;
				pageIndex = pageIn - 1;
				cardList = carService.getCardByPage(startIndex, LENGTH);
				return SUCCESS;
			}
		}
		if ("1".equals(pageFlag)) {
			if ((startIndex + LENGTH) > toltal) {
				cardList = carService.getCardByPage(startIndex, LENGTH);
				pageIndex = pageIn;
				return SUCCESS;
			} else {
				startIndex = startIndex + LENGTH;
				pageIndex = pageIn + 1;
				cardList = carService.getCardByPage(startIndex, LENGTH);
				return SUCCESS;
			}

		}
		return SUCCESS;
	}

	// TODO
	public String getReDiscussNotRead() {
		String hql = "from ReDiscuss r where r.deleteFlag=? and r.toId=? and r.state=? group by r.cardId";
		List<ReDiscuss> rs = reDiscussService
				.findEntityByHQL(hql, 1, fromId, 0);
		if (rs != null && !rs.isEmpty()) 
		for(int i=0;i<rs.size();i++){
			reDiscuss = rs.get(i);
			card = carService.getEntity(reDiscuss.getCardId());
			String hql1 = "from Discuss d where d.cardId=? and d.deleteFlag=?  ";
			List<Discuss> ds = discussService.findEntityByHQL(hql1,
					card.getCardId(), 1);
			if (ds != null && !ds.isEmpty())
				for(int j=0;j<ds.size();j++){
					discuss=ds.get(j);
					String hql2 = "from ReDiscuss d where d.discussId=? and deleteFlag=? and d.state=? order by d.reDiscussId";
					reDiscussList = reDiscussService.findEntityByHQL(hql2,
							discuss.getDiscussId(), 1, 0);
					if (reDiscussList==null||reDiscussList.isEmpty()||reDiscussList.size()==0) {
						continue;
					}else{
						reDiscuss.setState(1);
						reDiscussService.updateEntity(reDiscuss);
						String hql3 = "from ReDiscuss d where d.discussId=? and deleteFlag=?  order by d.reDiscussId desc";
						reDiscussList = reDiscussService.findEntityByHQL(hql3,
								discuss.getDiscussId(), 1);
						break;
					}
				}
		}
		return SUCCESS;
	}

	public String getCardListNotRead() {

		int pageIn = (int) pageIndex;
		int toltal = carService.getNotReadTotal(fromId);
		if (toltal % LENGTH == 0) {
			totalPage = toltal / LENGTH;
		} else {
			totalPage = toltal / LENGTH + 1;
		}
		startIndex = (int) startIndex;
		if ("2".equals(pageFlag)) {
			cardList = carService
					.getCardListNotRead(fromId, startIndex, LENGTH);
			pageIndex = pageIn;
			for (Card c : cardList) {
				this.changeState(c.getCardId());
			}
			return SUCCESS;
		}
		if ("0".equals(pageFlag)) {
			if ((startIndex - LENGTH) < 0) {
				cardList = carService.getCardListNotRead(fromId, startIndex,
						LENGTH);
				pageIndex = pageIn;
				for (Card c : cardList) {
					this.changeState(c.getCardId());
				}
				return SUCCESS;
			} else {
				startIndex = startIndex - LENGTH;
				pageIndex = pageIn - 1;
				cardList = carService.getCardListNotRead(fromId, startIndex,
						LENGTH);
				return SUCCESS;
			}
		}
		if ("1".equals(pageFlag)) {
			if ((startIndex + LENGTH) > toltal) {
				cardList = carService.getCardListNotRead(fromId, startIndex,
						LENGTH);
				pageIndex = pageIn;
				for (Card c : cardList) {
					this.changeState(c.getCardId());
				}
				return SUCCESS;
			} else {
				startIndex = startIndex + LENGTH;
				pageIndex = pageIn + 1;
				cardList = carService.getCardListNotRead(fromId, startIndex,
						LENGTH);
				for (Card c : cardList) {
					this.changeState(c.getCardId());
				}
				return SUCCESS;
			}

		}
		return SUCCESS;
	}

	public String getDiscussByCardId() {
		card = carService.getEntity(card.getCardId());
		discussList = discussService
				.findEntityByHQL(
						"from Discuss d   where d.deleteFlag=? and d.cardId=? order by d.discussId desc",
						1, card.getCardId());
		String hql2 = "from ReDiscuss d where d.deleteFlag=? and d.discussId=? order by d.reDiscussId desc";

		reDiscussList = reDiscussService.findEntityByHQL(hql2, 1,
				discuss.getDiscussId());
		return SUCCESS;
	}

	public String addDiscussPage() {
		card = carService.getEntity(card.getCardId());
		return SUCCESS;
	}

	public String addDiscuss() {
		// 1:学生 0：老师 2：未登录
		int flag;
		try {
			student = (Student) request.getSession().getAttribute("student");
			if (student != null) {
				// 身份为学生
				flag = 1;
				if (student.getEmail() == null) {
					flag = 2;
				}
			} else {
				flag = 2;
			}
		} catch (Exception e) {
			flag = 2;
		}
		if (flag != 1) {
			try {
				teacher = (Teacher) request.getSession()
						.getAttribute("teacher");
				if (teacher != null) {
					// 身份为老师
					flag = 0;
					if (teacher.getEmail() == null) {
						flag = 2;
					}
				} else {
					flag = 2;
				}
			} catch (Exception e) {
				flag = 2;
			}
		}
		if (flag == 2) {
			return LOGIN;
		}
		if (flag == 0) {
			discuss.setFromId(teacher.getEmail());
			discuss.setFromType(0);
			discuss.setFromName(teacher.getTeacherName());
		}
		if (flag == 1) {
			discuss.setFromId(student.getEmail());
			discuss.setFromType(1);
			discuss.setFromName(student.getName());
		}
		discuss.setCardId(card.getCardId());
		discussService.saveEntity(discuss);
		return SUCCESS;
	}

	public String addReDiscussPage() {
		String hql = "from ReDiscuss rd where rd.deleteFlag=? rd.discussId=?";
		reDiscussList = reDiscussService.findEntityByHQL(hql, 1,
				discuss.getDiscussId());
		return SUCCESS;
	}

	public String addReDiscuss() {
		// 1:学生 0：老师 2：未登录
		int flag;
		try {
			student = (Student) request.getSession().getAttribute("student");
			if (student != null) {
				// 身份为学生
				flag = 1;
				if (student.getEmail() == null) {
					flag = 2;
				}
			} else {
				flag = 2;
			}
		} catch (Exception e) {
			flag = 2;
		}
		if (flag != 1) {
			try {
				teacher = (Teacher) request.getSession()
						.getAttribute("teacher");
				if (teacher != null) {
					// 身份为老师
					flag = 0;
					if (teacher.getEmail() == null) {
						flag = 2;
					}
				} else {
					flag = 2;
				}
			} catch (Exception e) {
				flag = 2;
			}
		}
		if (flag == 2) {
			return LOGIN;
		}
		if (flag == 0) {
			reDiscuss.setFromId(teacher.getEmail());
			reDiscuss.setFromType(0);
			reDiscuss.setFromName(teacher.getTeacherName());
		}
		if (flag == 1) {
			reDiscuss.setFromId(student.getEmail());
			reDiscuss.setFromType(1);
			reDiscuss.setFromName(student.getName());
		}
		discuss = discussService.getEntity(discuss.getDiscussId());

		reDiscuss.setCardId(discuss.getCardId());
		reDiscuss.setDiscussId(discuss.getDiscussId());
		reDiscussService.saveEntity(reDiscuss);
		card = carService.getEntity(discuss.getCardId());
		String hql2 = "from ReDiscuss d where d.deleteFlag=? and d.discussId=? order by d.reDiscussId desc";
		reDiscussList = reDiscussService.findEntityByHQL(hql2, 1,
				discuss.getDiscussId());
		return SUCCESS;
	}

	public String studentGetMessageFromCard() {
		discussCount = discussService.studentGetMsgFromDiscuss(fromId);
		dataMap.clear();
		reDiscussCount = reDiscussService.studentGetMsgFromReDiscuss(fromId);
		Integer totalCount = discussCount + reDiscussCount;
		dataMap.put("discussCount", discussCount);
		dataMap.put("reDiscussCount", reDiscussCount);
		dataMap.put("totalCountMsg", totalCount);
		return SUCCESS;
	}

	/**
	 * 改变评论状态
	 * 
	 * @param discussList
	 */
	private void changeState(Integer cardId) {
		String hql = "from Discuss s where s.cardId=?";
		List<Discuss> discussList = discussService.findEntityByHQL(hql, cardId);
		for (Discuss s : discussList) {
			s.setState(1);
			discussService.updateEntity(s);
		}
	}

	/**
	 * @return the msg
	 */
	public String getMsg() {
		return msg;
	}

	/**
	 * @param msg
	 *            the msg to set
	 */
	public void setMsg(String msg) {
		this.msg = msg;
	}

	/**
	 * @return the card
	 */
	public Card getCard() {
		return card;
	}

	/**
	 * @param card
	 *            the card to set
	 */
	public void setCard(Card card) {
		this.card = card;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.struts2.interceptor.ServletRequestAware#setServletRequest(
	 * javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		this.request = arg0;
	}

	/**
	 * @return the startIndex
	 */
	public Integer getStartIndex() {
		return startIndex;
	}

	/**
	 * @param startIndex
	 *            the startIndex to set
	 */
	public void setStartIndex(Integer startIndex) {
		this.startIndex = startIndex;
	}

	/**
	 * @return the pageFlag
	 */
	public String getPageFlag() {
		return pageFlag;
	}

	/**
	 * @param pageFlag
	 *            the pageFlag to set
	 */
	public void setPageFlag(String pageFlag) {
		this.pageFlag = pageFlag;
	}

	/**
	 * @return the totalPage
	 */
	public Integer getTotalPage() {
		return totalPage;
	}

	/**
	 * @param totalPage
	 *            the totalPage to set
	 */
	public void setTotalPage(Integer totalPage) {
		this.totalPage = totalPage;
	}

	/**
	 * @return the cardList
	 */
	public List<Card> getCardList() {
		return cardList;
	}

	/**
	 * @param cardList
	 *            the cardList to set
	 */
	public void setCardList(List<Card> cardList) {
		this.cardList = cardList;
	}

	/**
	 * @return the pageIndex
	 */
	public Integer getPageIndex() {
		return pageIndex;
	}

	/**
	 * @param pageIndex
	 *            the pageIndex to set
	 */
	public void setPageIndex(Integer pageIndex) {
		this.pageIndex = pageIndex;
	}

	/**
	 * @return the discussList
	 */
	public List<Discuss> getDiscussList() {
		return discussList;
	}

	/**
	 * @param discussList
	 *            the discussList to set
	 */
	public void setDiscussList(List<Discuss> discussList) {
		this.discussList = discussList;
	}

	/**
	 * @return the discuss
	 */
	public Discuss getDiscuss() {
		return discuss;
	}

	/**
	 * @param discuss
	 *            the discuss to set
	 */
	public void setDiscuss(Discuss discuss) {
		this.discuss = discuss;
	}

	/**
	 * @return the reDiscussList
	 */
	public List<ReDiscuss> getReDiscussList() {
		return reDiscussList;
	}

	/**
	 * @param reDiscussList
	 *            the reDiscussList to set
	 */
	public void setReDiscussList(List<ReDiscuss> reDiscussList) {
		this.reDiscussList = reDiscussList;
	}

	/**
	 * @return the reDiscuss
	 */
	public ReDiscuss getReDiscuss() {
		return reDiscuss;
	}

	/**
	 * @param reDiscuss
	 *            the reDiscuss to set
	 */
	public void setReDiscuss(ReDiscuss reDiscuss) {
		this.reDiscuss = reDiscuss;
	}

	/**
	 * @return the discussId
	 */
	public String getDiscussId() {
		return discussId;
	}

	/**
	 * @param discussId
	 *            the discussId to set
	 */
	public void setDiscussId(String discussId) {
		this.discussId = discussId;
	}

	/**
	 * @return the cardId
	 */
	public String getCardId() {
		return cardId;
	}

	/**
	 * @param cardId
	 *            the cardId to set
	 */
	public void setCardId(String cardId) {
		this.cardId = cardId;
	}

	/**
	 * @return the fromId
	 */
	public String getFromId() {
		return fromId;
	}

	/**
	 * @param fromId
	 *            the fromId to set
	 */
	public void setFromId(String fromId) {
		this.fromId = fromId;
	}

	/**
	 * @return the discussCount
	 */
	public Integer getDiscussCount() {
		return discussCount;
	}

	/**
	 * @param discussCount
	 *            the discussCount to set
	 */
	public void setDiscussCount(Integer discussCount) {
		this.discussCount = discussCount;
	}

	/**
	 * @return the dataMap
	 */
	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	/**
	 * @param dataMap
	 *            the dataMap to set
	 */
	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	/**
	 * @return the reDiscussCount
	 */
	public Integer getReDiscussCount() {
		return reDiscussCount;
	}

	/**
	 * @param reDiscussCount
	 *            the reDiscussCount to set
	 */
	public void setReDiscussCount(Integer reDiscussCount) {
		this.reDiscussCount = reDiscussCount;
	}

	/**
	 * @return the totalCountMsg
	 */
	public Integer getTotalCountMsg() {
		return totalCountMsg;
	}

	/**
	 * @param totalCountMsg
	 *            the totalCountMsg to set
	 */
	public void setTotalCountMsg(Integer totalCountMsg) {
		this.totalCountMsg = totalCountMsg;
	}

}
